package com.ysd.lis.service.lab.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.PubEmployee;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.request.DeleteParam;
import com.ysd.lis.request.lab.LabProcessSetParam;
import com.ysd.lis.request.lab.LabTraceStateDto;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.lab.LabMainStateService;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * LAB_MAININFO的状态表 服务实现类
 * </p>
 *
 * @author Bai
 * @since 2024-01-16
 */
@Service
public class LabMainStateServiceImpl extends ServiceImpl<LabMainStateMapper, LabMainState> implements LabMainStateService {
    @Autowired
    LabMainStateMapper labMainStateMapper;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    LabReqStateMapper labReqStateMapper;
    @Autowired
    LabReqMainMapper labReqMainMapper;
    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    LabProcessSetMapper labProcessSetMapper;


    @Override
    public Result deleteMainState(DeleteParam param) {
        if (ToolsUtils.isEmpty(param)) {
            return Result.fail("入参不可为空！");
        }
        if (ToolsUtils.isEmpty(param.getIds())) {
            return Result.fail("入参不可为空！");
        }
        String ids = param.getIds();
        String[] array = ids.split(",");
        for (int i = 0; i < array.length; i++) {
            LambdaUpdateWrapper<LabMainState> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(LabMainState::getId, array[i]);
            lambdaUpdateWrapper.set(LabMainState::getDelFlag, 1);
            boolean b = this.update(null, lambdaUpdateWrapper);
            if (!b) {
                return Result.fail("删除失败！");
            }
        }
        return Result.succ(1, "删除成功！", null);
    }

    //获取状态
    @Override
    public String getMainState(String maininfoId) {
        LambdaQueryWrapper<LabMainState> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMainState::getDelFlag, 0).eq(LabMainState::getMaininfoId, maininfoId).orderByDesc(LabMainState::getSeq);
        LabMainState labReqState = labMainStateMapper.selectOne(queryWrapper);
        return labReqState.getStateCode();
    }


    /**
     * id: labmainInfo表中的id
     * reqNo : 申请号
     */
    // @Override
    // public Result getTraceRecList(LabMaininfo labMaininfo) {
    //     if (ToolsUtils.isEmpty(labMaininfo)) {
    //         return Result.fail("入参不可为空");
    //     }
    //     LabReqMain labReqMain = null;
    //     if (ToolsUtils.isNotEmpty(labMaininfo.getReqNo())) {
    //        // return Result.fail("条码号不可为空");
    //         String  reqNo = labMaininfo.getReqNo();
    //         LambdaQueryWrapper<LabReqMain> queryWrapper = new LambdaQueryWrapper<>();
    //         queryWrapper.select(LabReqMain::getId);
    //         queryWrapper.eq(LabReqMain::getReqNo, reqNo);
    //         labReqMain = labReqMainMapper.selectOne(queryWrapper);
    //     }
    //     String id = labMaininfo.getId();
    //     //获取需要展示的时间抽节点
    //     CommonPageDto commonPageDto = new CommonPageDto();
    //     commonPageDto.setCode("JYZT");
    //     Result re = sysBasDictDetailService.findDictDetailList(commonPageDto);
    //     List<Map<String, Object>> listDict = (List<Map<String, Object>>) re.getData();
    //     List<LabTraceStateDto> newList = new ArrayList<>();
    //     for (Map<String, Object> map : listDict) {
    //         if (map.containsKey("isStatShow") && map.get("isStatShow").equals("1")) {
    //             //newList.add(map);
    //             LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
    //             labTraceStateDto.setSn((Integer) map.get("sx"));
    //             labTraceStateDto.setStepName((String) map.get("name"));
    //             String code = (String) map.get("code");
    //             if (Integer.parseInt(code) <= 80 && null != labReqMain) {//获取上机中的状态
    //                 LambdaQueryWrapper<LabReqState> queryStateWrapper = new LambdaQueryWrapper<>();
    //                 queryStateWrapper.select(
    //                         LabReqState::getCreateTime,
    //                         LabReqState::getStateCode,
    //                         LabReqState::getSeq
    //                 );
    //                 queryStateWrapper.eq(LabReqState::getReqMainId, labReqMain.getId()).eq(LabReqState::getDelFlag, "0");
    //                 queryStateWrapper.eq(LabReqState::getStateCode, map.get("code"));
    //                 queryStateWrapper.orderByDesc(LabReqState::getCreateTime);
    //                List<LabReqState>  labReqStates = labReqStateMapper.selectList(queryStateWrapper);
    //                 if (ToolsUtils.isEmpty(labReqStates)) {
    //                     labTraceStateDto.setCompleted(false);
    //                 } else {
    //                     labTraceStateDto.setCompleted(true);
    //                     labTraceStateDto.setPrimary("primary");
    //                     labTraceStateDto.setCompleteDate(labReqStates.get(0).getCreateTime());
    //                 }
    //             }
    //             if(Integer.parseInt(code) <= 80 && ToolsUtils.isEmpty(labReqMain)){
    //                 labTraceStateDto.setCompleted(false);
    //             }
    //             if (Integer.parseInt(code) > 80) {//获取上机中的状态
    //                 LambdaQueryWrapper<LabMainState> queryMainWrapper = new LambdaQueryWrapper<>();
    //                 queryMainWrapper.select(
    //                         LabMainState::getCreateTime,
    //                         LabMainState::getStateCode,
    //                         LabMainState::getSeq
    //                 );
    //                 queryMainWrapper.eq(LabMainState::getMaininfoId, id).eq(LabMainState::getDelFlag, "0");
    //                 queryMainWrapper.eq(LabMainState::getStateCode, map.get("code"));
    //                 queryMainWrapper.orderByDesc(LabMainState::getCreateTime);
    //                 List<LabMainState> labMainStates = labMainStateMapper.selectList(queryMainWrapper);
    //                 if (ToolsUtils.isEmpty(labMainStates)) {
    //                     labTraceStateDto.setCompleted(false);
    //                 } else {
    //                     labTraceStateDto.setCompleted(true);
    //                     labTraceStateDto.setPrimary("primary");
    //                     labTraceStateDto.setCompleteDate(labMainStates.get(0).getCreateTime());
    //                 }
    //
    //             }
    //             newList.add(labTraceStateDto);
    //         }
    //     }
    //     return Result.succ(newList);
    // }
    @Override
    public Result getTraceRecTwoList(LabProcessSetParam input) {
        if (ToolsUtils.isEmpty(input)) {
            return Result.fail("入参不可为空");
        }
        List<LabTraceStateDto> newList = new ArrayList<>();

        MPJLambdaWrapper<LabReqState> reqStateWrapper = new MPJLambdaWrapper();
        reqStateWrapper.selectAll(LabReqState.class);
        reqStateWrapper.selectAs(SysUser::getRealname, LabReqState::getRealName);
        reqStateWrapper.leftJoin(SysUser.class, SysUser::getId, LabReqState::getCreator);
        reqStateWrapper.eq(LabReqState::getDelFlag, 0);
        reqStateWrapper.eq(LabReqState::getReqNo, input.getReqNo());
        reqStateWrapper.isNotNull(LabReqState::getStateCode);
        reqStateWrapper.ne(LabReqState::getStateCode, "");
        //申请状态
        List<LabReqState> labReqStateList = labReqStateMapper.selectList(reqStateWrapper);

        /*检验记录*/
        MPJLambdaWrapper<LabMaininfo> mainInfoWrapper = new MPJLambdaWrapper();
        mainInfoWrapper.eq(LabMaininfo::getDelFlag, 0);
        mainInfoWrapper.selectAll(LabMaininfo.class);
        mainInfoWrapper.eq(LabMaininfo::getReqNo, input.getReqNo());
        mainInfoWrapper.selectAs("tt1", SysUser::getRealname, LabMaininfo::getTestDoctorNa);
        mainInfoWrapper.selectAs("tt2", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
        mainInfoWrapper.selectAs("tt3", SysUser::getRealname, LabMaininfo::getSignerDoctorNa);
        mainInfoWrapper.selectAs("tt4", SysUser::getRealname, LabMaininfo::getSamplingDoctorNa);
        mainInfoWrapper.selectAs("tt5", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        mainInfoWrapper.selectAs("tt6", PubEmployee::getName, LabMaininfo::getReqDoctorNa);

        mainInfoWrapper.leftJoin(SysUser.class, "tt1", SysUser::getUsername, LabMaininfo::getTestDoctor);
        mainInfoWrapper.leftJoin(SysUser.class, "tt2", SysUser::getUsername, LabMaininfo::getChkDoctor);
        mainInfoWrapper.leftJoin(SysUser.class, "tt3", SysUser::getUsername, LabMaininfo::getSignerDoctor);
        mainInfoWrapper.leftJoin(SysUser.class, "tt4", SysUser::getUsername, LabMaininfo::getSamplingDoctor);
        mainInfoWrapper.leftJoin(SysUser.class, "tt5", SysUser::getUsername, LabMaininfo::getPrintDoctor);
        mainInfoWrapper.leftJoin(PubEmployee.class, "tt6", PubEmployee::getCode, LabMaininfo::getReqDoctor);

        List<LabMaininfo> mainInfoList = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(input.getReqNo())) {
            mainInfoList = labMaininfoMapper.selectList(mainInfoWrapper);
        }



        /*节点信息集合*/
        List<String> codeArrayList = labReqStateList.stream().map(p -> p.getStateCode()).collect(Collectors.toList());
        LambdaQueryWrapper<LabProcessSet> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LabProcessSet::getDelFlag, 0);
        //.in(LabProcessSet::getCode, ToolsUtils.isNotEmpty(codeArrayList) ? codeArrayList : Arrays.asList("!@#QWE"));

        List<LabProcessSet> processNodeList = labProcessSetMapper.selectList(wrapper);


        /*判断申请节点是否展示*/
        LabReqState isAppNode = labReqStateList.stream().filter(p -> ToolsUtils.isNotEmpty(p.getStateCode()) && "10".equals(p.getStateCode())).findFirst().orElse(null);

        if (ToolsUtils.isEmpty(isAppNode)) {
            LabProcessSet labProcessSet = ToolsUtils.isEmpty(processNodeList) ? null : processNodeList.stream().filter(p -> p.getCode().equals("10")).findFirst().orElse(null);
            if (ToolsUtils.isNotEmpty(labProcessSet) && ToolsUtils.isNotEmpty(labProcessSet.getIsShowState()) && labProcessSet.getIsShowState()) {
                LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
                labTraceStateDto.setStateCode("10");
                labTraceStateDto.setStateName(labProcessSet.getNodeName());
                try {
                    labTraceStateDto.setSortCode(Integer.parseInt("10"));
                } catch (Exception e) {
                    labTraceStateDto.setSortCode(99999);
                }
                LabMaininfo miEntry = ToolsUtils.isEmpty(mainInfoList) ? null : mainInfoList.stream().filter(a -> a.getReqNo().equals(input.getReqNo())).findFirst().orElse(null);
                if (ToolsUtils.isNotEmpty(miEntry)) {
                    labTraceStateDto.setOperateTime(ToolsUtils.isNotEmpty(miEntry.getReqTime()) ? miEntry.getReqTime() : null);
                    labTraceStateDto.setOperator(ToolsUtils.isNotEmpty(miEntry.getReqDoctorNa()) ? miEntry.getReqDoctorNa() : null);
                    labTraceStateDto.setRemark("申请");
                }
                if (ToolsUtils.isNotEmpty(input.getIsCloopShow())) {
                    if (input.getIsCloopShow() && ToolsUtils.isNotEmpty(labProcessSet.getIsCloopShow()) && labProcessSet.getIsCloopShow()) {
                        newList.add(labTraceStateDto);
                    }
                }
                if (ToolsUtils.isEmpty(input.getIsCloopShow())) {
                    newList.add(labTraceStateDto);
                }
            }
        }

        for (LabReqState reqState : labReqStateList) {
            LabProcessSet labProcessSet = ToolsUtils.isEmpty(processNodeList) ? null : processNodeList.stream().filter(p -> p.getCode().equals(reqState.getStateCode())).findFirst().orElse(null);
            if (labProcessSet == null) {
                continue;
            }
            if (ToolsUtils.isNotEmpty(labProcessSet.getIsShowState()) && !labProcessSet.getIsShowState()) {
                continue;
            }
            if (ToolsUtils.isNotEmpty(input.getIsCloopShow()) && input.getIsCloopShow() && (ToolsUtils.isEmpty(labProcessSet.getIsCloopShow()) || !labProcessSet.getIsCloopShow())) {
                continue;
            }

            LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
            labTraceStateDto.setStateCode(reqState.getStateCode());
            labTraceStateDto.setStateName(reqState.getStateValue());
            labTraceStateDto.setOperateTime(reqState.getCreateTime());
            labTraceStateDto.setOperator(reqState.getRealName());
            labTraceStateDto.setRemark(reqState.getRemark());

            if (ToolsUtils.isNotEmpty(mainInfoList) && mainInfoList.size() > 0 && ToolsUtils.isNotEmpty(reqState.getStateCode()) && "70".equals(reqState.getStateCode())) {
                if (ToolsUtils.isNotEmpty(reqState.getRptGroup()) && ToolsUtils.isNotEmpty(reqState.getSampleNo()) && ToolsUtils.isNotEmpty(reqState.getSampleda())) {
                    List<LabMaininfo> labMainInfoList = mainInfoList.stream().filter(a -> a.getRptGroup().equals(reqState.getRptGroup()) && a.getSampleNo().equals(reqState.getSampleNo()) && a.getSampleda().equals(reqState.getSampleda())).collect(Collectors.toList());
                    if (ToolsUtils.isNotEmpty(labMainInfoList) && labMainInfoList.size() > 0) {
                        LabMaininfo entry = labMainInfoList.get(0);
                        labTraceStateDto.setOperator(entry.getSignerDoctorNa());
                    }
                }
            }

            if (ToolsUtils.isNotEmpty(mainInfoList) && mainInfoList.size() > 0 && ToolsUtils.isNotEmpty(reqState.getStateCode()) && "90".equals(reqState.getStateCode())) {
                if (ToolsUtils.isNotEmpty(reqState.getRptGroup()) && ToolsUtils.isNotEmpty(reqState.getSampleNo()) && ToolsUtils.isNotEmpty(reqState.getSampleda())) {
                    List<LabMaininfo> labMainInfoList = mainInfoList.stream().filter(a -> a.getRptGroup().equals(reqState.getRptGroup()) && a.getSampleNo().equals(reqState.getSampleNo()) && a.getSampleda().equals(reqState.getSampleda())).collect(Collectors.toList());
                    if (ToolsUtils.isNotEmpty(labMainInfoList) && labMainInfoList.size() > 0) {
                        LabMaininfo entry = labMainInfoList.get(0);
                        labTraceStateDto.setOperator(entry.getTestDoctorNa());
                    }
                }
            }

            if (ToolsUtils.isNotEmpty(mainInfoList) && mainInfoList.size() > 0 && ToolsUtils.isNotEmpty(reqState.getStateCode()) && "100".equals(reqState.getStateCode())) {
                if (ToolsUtils.isNotEmpty(reqState.getRptGroup()) && ToolsUtils.isNotEmpty(reqState.getSampleNo()) && ToolsUtils.isNotEmpty(reqState.getSampleda())) {
                    List<LabMaininfo> labMainInfoList = mainInfoList.stream().filter(a -> a.getRptGroup().equals(reqState.getRptGroup()) && a.getSampleNo().equals(reqState.getSampleNo()) && a.getSampleda().equals(reqState.getSampleda())).collect(Collectors.toList());
                    if (ToolsUtils.isNotEmpty(labMainInfoList) && labMainInfoList.size() > 0) {
                        LabMaininfo entry = labMainInfoList.get(0);
                        labTraceStateDto.setOperator(entry.getChkDoctorNa());
                    }
                }
            }

            try {
                labTraceStateDto.setSortCode(Integer.parseInt(reqState.getStateCode()));
            } catch (Exception e) {
                labTraceStateDto.setSortCode(99999);
            }
            newList.add(labTraceStateDto);
        }
        // 根据sortCode进行分组，然后取operateTime最新的一条数据
        Collection<LabTraceStateDto> result = newList.stream()
                .collect(Collectors.toMap(
                        LabTraceStateDto::getSortCode,
                        dto -> dto,
                        BinaryOperator.maxBy(Comparator.comparing(LabTraceStateDto::getOperateTime))
                )).values();

        // 将结果转换为List并排序
        List<LabTraceStateDto> sortedResult = result.stream()
                .sorted(Comparator.comparing(LabTraceStateDto::getSortCode))
                .collect(Collectors.toList());
        return Result.succ(sortedResult);
    }

    @Override
    public Result getClosedLoopList(LabProcessSetParam input) {
        if (ToolsUtils.isEmpty(input)) {
            return Result.fail("入参不可为空");
        }
        List<LabTraceStateDto> newList = new ArrayList<>();

        MPJLambdaWrapper<LabReqState> reqStateWrapper = new MPJLambdaWrapper();
        reqStateWrapper.selectAll(LabReqState.class);
        reqStateWrapper.selectAs(SysUser::getRealname, LabReqState::getRealName);
        reqStateWrapper.leftJoin(SysUser.class, SysUser::getId, LabReqState::getCreator);
        reqStateWrapper.eq(LabReqState::getDelFlag, 0);
        reqStateWrapper.eq(LabReqState::getReqNo, input.getReqNo());
        reqStateWrapper.isNotNull(LabReqState::getStateCode);
        reqStateWrapper.ne(LabReqState::getStateCode, "");
        //申请状态
        List<LabReqState> labReqStateList = labReqStateMapper.selectList(reqStateWrapper);

        /*检验记录*/
        MPJLambdaWrapper<LabMaininfo> mainInfoWrapper = new MPJLambdaWrapper();
        mainInfoWrapper.eq(LabMaininfo::getDelFlag, 0);
        mainInfoWrapper.selectAll(LabMaininfo.class);
        mainInfoWrapper.eq(LabMaininfo::getReqNo, input.getReqNo());
        mainInfoWrapper.selectAs("tt1", SysUser::getRealname, LabMaininfo::getTestDoctorNa);
        mainInfoWrapper.selectAs("tt2", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
        mainInfoWrapper.selectAs("tt3", SysUser::getRealname, LabMaininfo::getSignerDoctorNa);
        mainInfoWrapper.selectAs("tt4", SysUser::getRealname, LabMaininfo::getSamplingDoctorNa);
        mainInfoWrapper.selectAs("tt5", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        mainInfoWrapper.selectAs("tt6", PubEmployee::getName, LabMaininfo::getReqDoctorNa);

        mainInfoWrapper.leftJoin(SysUser.class, "tt1", SysUser::getUsername, LabMaininfo::getTestDoctor);
        mainInfoWrapper.leftJoin(SysUser.class, "tt2", SysUser::getUsername, LabMaininfo::getChkDoctor);
        mainInfoWrapper.leftJoin(SysUser.class, "tt3", SysUser::getUsername, LabMaininfo::getSignerDoctor);
        mainInfoWrapper.leftJoin(SysUser.class, "tt4", SysUser::getUsername, LabMaininfo::getSamplingDoctor);
        mainInfoWrapper.leftJoin(SysUser.class, "tt5", SysUser::getUsername, LabMaininfo::getPrintDoctor);
        mainInfoWrapper.leftJoin(PubEmployee.class, "tt6", PubEmployee::getCode, LabMaininfo::getReqDoctor);

        List<LabMaininfo> mainInfoList = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(input.getReqNo())) {
            mainInfoList = labMaininfoMapper.selectList(mainInfoWrapper);
        }



        /*节点信息集合*/
        List<String> codeArrayList = labReqStateList.stream().map(p -> p.getStateCode()).collect(Collectors.toList());
        LambdaQueryWrapper<LabProcessSet> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LabProcessSet::getDelFlag, 0);
        //.in(LabProcessSet::getCode, ToolsUtils.isNotEmpty(codeArrayList) ? codeArrayList : Arrays.asList("!@#QWE"));

        List<LabProcessSet> processNodeList = labProcessSetMapper.selectList(wrapper);

        //processNodeList过滤出isCloopShow和isShowState 为true的数据
        //processNodeList = processNodeList.stream().filter(p -> p.getIsCloopShow() && p.getIsShowState()).collect(Collectors.toList());

        processNodeList = Optional.ofNullable(processNodeList)
                .orElse(Collections.emptyList())
                .stream()
                .filter(Objects::nonNull)
                .filter(p -> Boolean.TRUE.equals(p.getIsCloopShow())
                        && Boolean.TRUE.equals(p.getIsShowState()))
                .collect(Collectors.toList());


        //过滤出labReqStateList的stateCode 不在processNodeList 的code的数据
        List<LabProcessSet> collect = processNodeList.stream().filter(p -> ToolsUtils.isNotEmpty(p.getCode()) && !codeArrayList.contains(p.getCode())).collect(Collectors.toList());
        LabMaininfo miEntry = ToolsUtils.isEmpty(mainInfoList) ? null : mainInfoList.stream().filter(a -> a.getReqNo().equals(input.getReqNo())).findFirst().orElse(null);
        for (LabProcessSet p : collect) {

            //TUDO
            if (ToolsUtils.isNotEmpty(miEntry)) {

                switch (p.getCode()) {
                    case "10":
                        if (ToolsUtils.isNotEmpty(miEntry.getReqTime())) {
                            LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
                            labTraceStateDto.setStateCode(p.getCode());
                            labTraceStateDto.setStateName(p.getNodeName());
                            try {
                                labTraceStateDto.setSortCode(Integer.parseInt(p.getCode()));
                            } catch (Exception e) {
                                labTraceStateDto.setSortCode(99999);
                            }
                            labTraceStateDto.setOperateTime(miEntry.getReqTime());
                            labTraceStateDto.setOperator(miEntry.getReqDoctorNa());
                            labTraceStateDto.setRemark("申请");
                            newList.add(labTraceStateDto);
                        }
                        break;
                    case "40":
                        if (ToolsUtils.isNotEmpty(miEntry.getSamplingTime())) {
                            LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
                            labTraceStateDto.setStateCode(p.getCode());
                            labTraceStateDto.setStateName(p.getNodeName());
                            try {
                                labTraceStateDto.setSortCode(Integer.parseInt(p.getCode()));
                            } catch (Exception e) {
                                labTraceStateDto.setSortCode(99999);
                            }
                            labTraceStateDto.setOperateTime(miEntry.getSamplingTime());
                            labTraceStateDto.setOperator(miEntry.getSamplingDoctorNa());
                            labTraceStateDto.setRemark("采样");
                            newList.add(labTraceStateDto);
                        }
                        break;
                    case "70":
                        if (ToolsUtils.isNotEmpty(miEntry.getSignTime())) {
                            LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
                            labTraceStateDto.setStateCode(p.getCode());
                            labTraceStateDto.setStateName(p.getNodeName());
                            try {
                                labTraceStateDto.setSortCode(Integer.parseInt(p.getCode()));
                            } catch (Exception e) {
                                labTraceStateDto.setSortCode(99999);
                            }
                            labTraceStateDto.setOperateTime(miEntry.getSignTime());
                            labTraceStateDto.setOperator(miEntry.getSignerDoctorNa());
                            labTraceStateDto.setRemark("签收");
                            newList.add(labTraceStateDto);
                        }
                        break;
                    case "90":
                        if (ToolsUtils.isNotEmpty(miEntry.getTestTime())) {
                            LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
                            labTraceStateDto.setStateCode(p.getCode());
                            labTraceStateDto.setStateName(p.getNodeName());
                            try {
                                labTraceStateDto.setSortCode(Integer.parseInt(p.getCode()));
                            } catch (Exception e) {
                                labTraceStateDto.setSortCode(99999);
                            }
                            labTraceStateDto.setOperateTime(miEntry.getTestTime());
                            labTraceStateDto.setOperator(miEntry.getTestDoctorNa());
                            labTraceStateDto.setRemark("上机");
                            newList.add(labTraceStateDto);
                        }
                        break;
                    case "100":
                        if (ToolsUtils.isNotEmpty(miEntry.getChkTime())) {
                            LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
                            labTraceStateDto.setStateCode(p.getCode());
                            labTraceStateDto.setStateName(p.getNodeName());
                            try {
                                labTraceStateDto.setSortCode(Integer.parseInt(p.getCode()));
                            } catch (Exception e) {
                                labTraceStateDto.setSortCode(99999);
                            }
                            labTraceStateDto.setOperateTime(miEntry.getChkTime());
                            labTraceStateDto.setOperator(miEntry.getChkDoctorNa());
                            labTraceStateDto.setRemark("签收");
                            newList.add(labTraceStateDto);
                        }
                        break;
                    case "140":
                        if (ToolsUtils.isNotEmpty(miEntry.getUnchkTime())) {
                            LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
                            labTraceStateDto.setStateCode(p.getCode());
                            labTraceStateDto.setStateName(p.getNodeName());
                            try {
                                labTraceStateDto.setSortCode(Integer.parseInt(p.getCode()));
                            } catch (Exception e) {
                                labTraceStateDto.setSortCode(99999);
                            }
                            labTraceStateDto.setOperateTime(miEntry.getUnchkTime());
                            labTraceStateDto.setOperator(miEntry.getUnChkDoctorNa());
                            labTraceStateDto.setRemark("签收");
                            newList.add(labTraceStateDto);
                        }
                        break;
                    default:
                        break;
                }


            }


        }


        // /*判断申请节点是否展示*/
        // LabReqState isAppNode = labReqStateList.stream().filter(p -> ToolsUtils.isNotEmpty(p.getStateCode()) && "10".equals(p.getStateCode())).findFirst().orElse(null);
        //
        // if (ToolsUtils.isEmpty(isAppNode)) {
        //     LabProcessSet labProcessSet = ToolsUtils.isEmpty(processNodeList) ? null : processNodeList.stream().filter(p -> p.getCode().equals("10")).findFirst().orElse(null);
        //     if (ToolsUtils.isNotEmpty(labProcessSet) && ToolsUtils.isNotEmpty(labProcessSet.getIsShowState()) && labProcessSet.getIsShowState()) {
        //         LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
        //         labTraceStateDto.setStateCode("10");
        //         labTraceStateDto.setStateName(labProcessSet.getNodeName());
        //         try {
        //             labTraceStateDto.setSortCode(Integer.parseInt("10"));
        //         } catch (Exception e) {
        //             labTraceStateDto.setSortCode(99999);
        //         }
        //         LabMaininfo miEntry = ToolsUtils.isEmpty(mainInfoList) ? null : mainInfoList.stream().filter(a -> a.getReqNo().equals(input.getReqNo())).findFirst().orElse(null);
        //         if (ToolsUtils.isNotEmpty(miEntry)) {
        //             labTraceStateDto.setOperateTime(ToolsUtils.isNotEmpty(miEntry.getReqTime()) ? miEntry.getReqTime() : null);
        //             labTraceStateDto.setOperator(ToolsUtils.isNotEmpty(miEntry.getReqDoctorNa()) ? miEntry.getReqDoctorNa() : null);
        //             labTraceStateDto.setRemark("申请");
        //         }
        //         if (ToolsUtils.isNotEmpty(input.getIsCloopShow())) {
        //             if (input.getIsCloopShow() && ToolsUtils.isNotEmpty(labProcessSet.getIsCloopShow()) && labProcessSet.getIsCloopShow()) {
        //                 newList.add(labTraceStateDto);
        //             }
        //         }
        //         if (ToolsUtils.isEmpty(input.getIsCloopShow())) {
        //             newList.add(labTraceStateDto);
        //         }
        //     }
        // }

        for (LabReqState reqState : labReqStateList) {
            LabProcessSet labProcessSet = ToolsUtils.isEmpty(processNodeList) ? null : processNodeList.stream().filter(p -> p.getCode().equals(reqState.getStateCode())).findFirst().orElse(null);
            if (labProcessSet == null) {
                continue;
            }
            if (ToolsUtils.isNotEmpty(labProcessSet.getIsShowState()) && !labProcessSet.getIsShowState()) {
                continue;
            }
            if (ToolsUtils.isNotEmpty(input.getIsCloopShow()) && input.getIsCloopShow() && (ToolsUtils.isEmpty(labProcessSet.getIsCloopShow()) || !labProcessSet.getIsCloopShow())) {
                continue;
            }

            LabTraceStateDto labTraceStateDto = new LabTraceStateDto();
            labTraceStateDto.setStateCode(reqState.getStateCode());
            labTraceStateDto.setStateName(reqState.getStateValue());
            labTraceStateDto.setOperateTime(reqState.getCreateTime());
            labTraceStateDto.setOperator(reqState.getRealName());
            labTraceStateDto.setRemark(reqState.getRemark());

            if (ToolsUtils.isNotEmpty(mainInfoList) && mainInfoList.size() > 0 && ToolsUtils.isNotEmpty(reqState.getStateCode()) && "70".equals(reqState.getStateCode())) {
                if (ToolsUtils.isNotEmpty(reqState.getRptGroup()) && ToolsUtils.isNotEmpty(reqState.getSampleNo()) && ToolsUtils.isNotEmpty(reqState.getSampleda())) {
                    List<LabMaininfo> labMainInfoList = mainInfoList.stream().filter(a -> a.getRptGroup().equals(reqState.getRptGroup()) && a.getSampleNo().equals(reqState.getSampleNo()) && a.getSampleda().equals(reqState.getSampleda())).collect(Collectors.toList());
                    if (ToolsUtils.isNotEmpty(labMainInfoList) && labMainInfoList.size() > 0) {
                        LabMaininfo entry = labMainInfoList.get(0);
                        labTraceStateDto.setOperator(entry.getSignerDoctorNa());
                    }
                }
            }

            if (ToolsUtils.isNotEmpty(mainInfoList) && mainInfoList.size() > 0 && ToolsUtils.isNotEmpty(reqState.getStateCode()) && "90".equals(reqState.getStateCode())) {
                if (ToolsUtils.isNotEmpty(reqState.getRptGroup()) && ToolsUtils.isNotEmpty(reqState.getSampleNo()) && ToolsUtils.isNotEmpty(reqState.getSampleda())) {
                    List<LabMaininfo> labMainInfoList = mainInfoList.stream().filter(a -> a.getRptGroup().equals(reqState.getRptGroup()) && a.getSampleNo().equals(reqState.getSampleNo()) && a.getSampleda().equals(reqState.getSampleda())).collect(Collectors.toList());
                    if (ToolsUtils.isNotEmpty(labMainInfoList) && labMainInfoList.size() > 0) {
                        LabMaininfo entry = labMainInfoList.get(0);
                        labTraceStateDto.setOperator(entry.getTestDoctorNa());
                    }
                }
            }

            if (ToolsUtils.isNotEmpty(mainInfoList) && mainInfoList.size() > 0 && ToolsUtils.isNotEmpty(reqState.getStateCode()) && "100".equals(reqState.getStateCode())) {
                if (ToolsUtils.isNotEmpty(reqState.getRptGroup()) && ToolsUtils.isNotEmpty(reqState.getSampleNo()) && ToolsUtils.isNotEmpty(reqState.getSampleda())) {
                    List<LabMaininfo> labMainInfoList = mainInfoList.stream().filter(a -> a.getRptGroup().equals(reqState.getRptGroup()) && a.getSampleNo().equals(reqState.getSampleNo()) && a.getSampleda().equals(reqState.getSampleda())).collect(Collectors.toList());
                    if (ToolsUtils.isNotEmpty(labMainInfoList) && labMainInfoList.size() > 0) {
                        LabMaininfo entry = labMainInfoList.get(0);
                        labTraceStateDto.setOperator(entry.getChkDoctorNa());
                    }
                }
            }

            try {
                labTraceStateDto.setSortCode(Integer.parseInt(reqState.getStateCode()));
            } catch (Exception e) {
                labTraceStateDto.setSortCode(99999);
            }
            newList.add(labTraceStateDto);
        }
        // 根据sortCode进行分组，然后取operateTime最新的一条数据
        Collection<LabTraceStateDto> result = newList.stream()
                .collect(Collectors.toMap(
                        LabTraceStateDto::getSortCode,
                        dto -> dto,
                        BinaryOperator.maxBy(Comparator.comparing(LabTraceStateDto::getOperateTime))
                )).values();

        // 将结果转换为List并排序
        List<LabTraceStateDto> sortedResult = result.stream()
                .sorted(Comparator.comparing(LabTraceStateDto::getSortCode))
                .collect(Collectors.toList());
        return Result.succ(sortedResult);
    }
}